/**!
 * 用户注册
 * author: shenyh
 * date:2016.12.13
 */
(function(win, $) {
    var $registerForm = $('#registerForm'),
        $weakPwd = $('.ewb-weak', $registerForm),
        $mediumPwd = $('.ewb-medium', $registerForm),
        $strongPwd = $('.ewb-strong', $registerForm),
        $delPwd = $('.ewb-form-safe span', $registerForm),
        $submitBtn = $('.ewb-form-btn', $registerForm);
    $.validator.setDefaults();
    //注册类型切换
    $(".rdosection input").click(function(event) {
        /* Act on the event */
        var v = $(this).val();
        if (v == 1) {
            $("input[name=userName]").attr("placeholder", "请使用身份证号码");
			$("#fwjgxy").attr("style","display:none;");
        } else if(v==2){
            $("input[name=userName]").attr("placeholder", "请使用统一社会信用代码或者组织机构代码");
			$("#fwjgxy").attr("style","display:default;");
		}else{
            $("input[name=userName]").attr("placeholder", "请使用身份证号码");
			$("#fwjgxy").attr("style","display:none;");
        }
    });
    $(".ewb-form-btn").click(function(event) {
        if ($(".ewb-form-checkbox input").is(":checked")) {
            if ($("#registerForm").valid()) {
                //序列化表单元素
                var pms = $registerForm.serializeObject();
				//console.log('{userName:"' + pms.userName + '",passWord:"' + pms.password + '",contacts:"' + pms.contacts + '",mobile:"' + pms.mobile + '",phone:"' + pms.phone + '",QQ:"' + pms.QQ + '"' + ',registType:"' + pms.rdoregister + '",isfwjg:"' + pms.fwjg + '"}');
                //用户唯一标识存入cookie,作为输入参数
                //清空val值
                $('.ewb-form-input').val("");
                // ajax
                var registUrl = Util.AjaxRUrl + 'regist';
                //console.log(registUrl);
                $.ajax({
                    url: registUrl,
                    type: "post",
                    data: {
                        param: '{userName:"' + pms.userName + '",passWord:"' +  hex_md5(pms.password) + '",contacts:"' + pms.contacts + '",mobile:"' + pms.mobile + '",phone:"' + pms.phone + '",QQ:"' + pms.QQ + '"' + ',registType:"' + pms.rdoregister + '",isfwjg:"' + pms.fwjg + '"}'
                    },
                    success: function(data) {
                        var data1 = $.parseJSON(data);
                        if (data1) {
                            var status = data1.returnInfo.isok;
                            switch (status) {
                                case "1":
                                    alert("注册成功!");
									reglogin(pms.userName,pms.password);
                                    break;
                                case "2":
                                    alert("程序异常");
                                    break;
                                case "3":
                                    alert("用户名已存在");
                                    break;
                                default:
                                    break;
                            }
                        }
                    },
                    error: function(XMLHttpRequest, txtStatus, errorThrown) {
                        //console.log(XMLHttpRequest);
                    }
                });
            }
        } else {
            alert("请确认我已阅读")
        }

    });
	function reglogin(username,password){
		var UserLoginUrl = Util.AjaxRUrl + 'UserLogin';
		$.ajax({
			url: UserLoginUrl,
			type: "post",
			data: {
				param: '{loginId:"' + username + '",passWord:"' +  hex_md5(password) + '"}'
			},
			success: function(data) {
				var data1 = $.parseJSON(data);
				if (data1.UserGuid) {
					var UserGuid = data1.UserGuid;
					var userName = data1.userName;
					if ($(".ewb-login-node input").is(":checked")) {
						$.cookie('the_userid', UserGuid, { expires: 7, path: "/" }); //将用户的唯一标识存入cookie
						$.cookie('userName', userName, { expires: 7, path: "/" });
					} else {
						//当没有指明cookie时间时，所创建的cookie有效期默认到用户浏览器关闭止，故被称为会话cookie。
						$.cookie('the_userid', UserGuid, { path: "/" }); //将用户的唯一标识存入cookie
						$.cookie('userName', userName, { path: "/" });
					}
					alert("登录成功");
					parent.layer.closeAll(); //关闭登录窗
					//parent.location.reload();
					parent.location = "/personalHome.html";
				} else {
					alert("登录失败；请确认账户与密码")
				}
			},
			error: function(XMLHttpRequest, txtStatus, errorThrown) {
				//console.log(XMLHttpRequest);
			}
		});
	}
    //表单验证
    // $.validator.setDefaults({
    //     submitHandler: function() {


    //     }
    // });
    //自定义验证方法
    // 手机号码和固话规则
    $.validator.addMethod('isPhone', function(value, element) {
        var length = value.length;
        var mobile = /^1[34578]\d{9}$/;
        var tel = /0\d{2,3}-\d{5,9}|0\d{2,3}-\d{5,9}/;
        return this.optional(element) || (tel.test(value) || mobile.test(value));
    }, '请正确填写您的联系电话');

    // 用户名支持字母、数字、下划线组合，需以字母开头
    $.validator.addMethod('isUser', function(value, element) {
        var t = $(".rdosection input:checked").val();
        var valided = false;
        if (t == 1||t == 3) //个人注册或专家注册
        {
            // /^[a-zA-Z]+[a-zA-Z0-9_]*$/;
            if(value.length==15||value.length==18)
            {
                valided = identityCodeValid(value.toUpperCase());
            }
        } else {
            var length = value.length;
            //var username = /^[A-Za-z0-9]+$/;       
            if (length == 9) {
                //组织结构代码
                valided = checkZCode(value, $(element));
            } else if (length == 18) {
                //社会信用代码
                valided = checkSXCode(value);
            }

        }
        ///^[a-zA-Z]+[a-zA-Z0-9_]*$/;
        return this.optional(element) || valided;
    }, '格式不正确'); //需字母开头,数字和下划线
    function checkZCode(CODE, $this) {
        var patrn = /^[0-9A-Z]+$/;
        if (patrn.test(CODE) == false) {
            $this.val("");
            //alert("组织机构代码只可为数字或大写拉丁字母");
            return false;

        } else {
            var lastpatrn = /^[0-9X]+$/;
            var checkcode = CODE.substring(8, 9);
            if (lastpatrn.test(checkcode) == false) {
                //alert("组织机构代码最后一位只可为数字或大写拉丁字母:X");
                return false;
            } else {
                var ancode;
                var ancodevalue;
                var total = 0;
                var weightedfactors = [3, 7, 9, 10, 5, 8, 4, 2]; //加权因子
                var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                for (var i = 0; i < CODE.length - 1; i++) {

                    ancode = CODE.substring(i, i + 1);
                    ancodevalue = str.indexOf(ancode);
                    total = total + ancodevalue * weightedfactors[i];
                }
                var ucheckcode = 11 - total % 11;
                if (ucheckcode == 10)
                    ucheckcode = 'X';
                if (ucheckcode == 11)
                    ucheckcode = '0';
                if (checkcode != ucheckcode) {
                    //alert("组织机构代码结构错误");
                    return false;
                }
            }
            return true;
        }
    }

    function checkSXCode(SXCode) {
        var CODE1 = SXCode;
        var CODE = CODE1.substring(8, 17);
        var patrn1 = /^[0-9A-Z]+$/; //大小写
        if ((CODE1.length != 18) || (patrn1.test(CODE1) == false)) {
            //alert("统一社会信用代码不能输入小写");
            return false;
        } else {
            var patrn = /^[0-9A-Z]+$/;
            if (patrn.test(CODE) == false) {
                //alert("统一社会信用代码不正确");
                return false;
            } else {
                var lastpatrn = /^[0-9X]+$/;
                var checkcode = CODE.substring(8, 9);
                if (lastpatrn.test(checkcode) == false) {
                    //alert("统一社会信用代码不正确");
                    return false;
                } else {
                    var ancode;
                    var ancodevalue;
                    var total = 0;
                    var weightedfactors = [3, 7, 9, 10, 5, 8, 4, 2]; //加权因子
                    var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                    for (var i = 0; i < CODE.length - 1; i++) {
                        ancode = CODE.substring(i, i + 1);
                        ancodevalue = str.indexOf(ancode);
                        total = total + ancodevalue * weightedfactors[i];
                    }
                    var ucheckcode = 11 - total % 11;
                    if (ucheckcode == 10)
                        ucheckcode = 'X';
                    if (ucheckcode == 11)
                        ucheckcode = '0';
                    if (checkcode != ucheckcode) {
                        //alert("统一社会信用代码不正确");
                        return false;
                    }
                }
                return true;
            }
        }
    }

    function identityCodeValid(code) {
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" };
        var pass = true;
        if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
            pass = false;
        } else if (!city[code.substr(0, 2)]) {
            pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    pass = false;
                }
            }
        }
        return pass;
    }
    // 密码不能有空格
    $.validator.addMethod('isPwd', function(value, element) {
        var length = value.length;
        var passWord = /^\S*$/;
        return this.optional(element) || passWord.test(value);
    }, '密码不能有空格');

    //密码强度验证
    $('#password').on('keydown', function() {

        var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
        var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
        var weakRegex = new RegExp("(?=.{6,}).*", "g");

        if (false == weakRegex.test($(this).val())) {
            $delPwd.removeClass('cur');
            //密码小于六位的时候，密码强度图片都为灰色 
        } else if (strongRegex.test($(this).val())) {
            $delPwd.removeClass('cur');
            $strongPwd.addClass('cur');
            //密码为八位及以上并且字母数字特殊字符三项都包括,强度最强 
        } else if (mediumRegex.test($(this).val())) {
            $delPwd.removeClass('cur');
            $mediumPwd.addClass('cur');
            //密码为七位及以上并且字母、数字、特殊字符三项中有两项，强度是中等 
        } else {
            $delPwd.removeClass('cur');
            $weakPwd.addClass('cur');
            //如果密码为6为及以下，就算字母、数字、特殊字符三项都包括，强度也是弱的 
        }
        return true;
    });

    // 表单验证规则
    var validator = $registerForm.validate({
        rules: {
            userName: {
                required: true,
                rangelength: [3, 20],
                isUser: true
            },
            password: {
                required: true,
                isPwd: true,
                minlength: 6,
                maxlength: 20
            },
            confirmpwd: {
                required: true,
                isPwd: true,
                minlength: 6,
                maxlength: 20,
                equalTo: "#password"
            },
            contacts: "required",
            mobile: {
                required: true,
                isPhone: true
            },
            phone: {
                required: true,
                isPhone: true
            },
            QQ: {
                required: true,
                digits: true
            }
        },
        messages: {
            userName: {
                required: "请输入用户名",
                rangelength: "无效用户名"
            },
            password: {
                required: "请输入密码",
                minlength: "密码最少6个字符",
                maxlength: "密码最多20个字符"
            },
            confirmpwd: {
                required: "请输入确认密码",
                minlength: "密码最少6个字符",
                maxlength: "用户名最多20个字符",
                equalTo: "两次输入密码须一致"
            },
            contacts: "请输入联系人",
            mobile: {
                required: "请输入联系电话"
            },
            phone: {
                required: "请输入固定电话"
            },
            QQ: {
                required: "请输入QQ号",
                digits: "请输入正确的QQ号"
            }
        }
    });
}(this, jQuery))
